<template>
  <div class="project-type-role-manage">
    <el-button type="primary" size="mini" @click="handleClickCreate" class="mb_12" v-if="roleManageAuth">{{ $t('common.button.createRole') }}</el-button>
    <!-- 角色管理 -->
    <el-table v-table-style v-loading="listLoading" :data="dataList" max-height="500" header-row-class-name="common-list-table-header__v2" border>
      <template slot="empty">
        <BaseListForNoData v-show="!listLoading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      </template>

      <el-table-column v-for="(column, index) in columns" :key="`${column.displayName}_${index}`" :prop="column.fieldName" :label="column.displayName" show-overflow-tooltip>
        <template slot-scope="scope">
          <template v-if="column.formType === 'user'">
            <template v-if="isOpenData">
              <template v-if="Array.isArray(scope.row[column.fieldName])">
                <open-data v-for="item in scope.row[column.fieldName]" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                <open-data type="userName" :openid="scope.row[column.fieldName] && scope.row[column.fieldName].staffId"></open-data>
              </template>
            </template>

            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
          <template v-else>
            {{ getNestedProperty(scope.row, column.fieldName) }}
          </template>
        </template>
      </el-table-column>

      <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="180" v-if="showOperate">
        <template slot-scope="scope">
          <!-- type 1 系统角色  2 自定义角色 -->
          <!-- flag  0 自定义角色 1 项目管理员 2 任务负责人 -->
          <span class="operation-button edit" v-if="scope.row.flag != 1" @click="chooseUser(scope.row)">{{ $t('calendar.detail.addPeople') }}</span>
          <span class="operation-button edit ml_12" v-if="scope.row.type != 1" @click="handleEditRole(scope.row)">{{ $t('common.base.edit') }}</span>
          <span class="operation-button ml_12 delete" v-if="scope.row.type != 1" @click="handleDeleteRole(scope.row)">{{ $t('common.base.delete') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <create-auth ref="CreateAuthModal" :authActionList="authActionList" :dataAuthList="dataAuthList" @submit="submit"></create-auth>
  </div>
</template>
<script>
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser';
import { projectTypeRoleList, projectTypeAddRole, roleDelete, authList, roleAdd, roleDetail, roleUpdate, getSearchUserList, getSearchMoreUserList, getMemberList, getSelectProjectTeamList } from '@src/api/ProjectManage.ts';

import { isOpenData, toast } from '@src/util/platform';
import { MessageBox } from 'element-ui';

import i18n from '@src/locales';

import { jumpProjectTypeDetail } from '@src/modules/projectManage/productTypeUtils/jumpPage.js';

import { fixRole } from '@src/modules/projectManage/productTypeUtils/fixFields.js';
import CreateAuth from '@src/modules/setting/projectManage/components/AuthSetting/components/CreateAuth.vue'
import locales from '@src/locales';


export default {
  name: 'project-type-role-manage',
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    projectId: {
      type: String | Number,
      default: '',
    },
    // 权限
    btnAuth: {
      type: Object,
      default: () => ({}),
    },
  },
  components:  {
    CreateAuth,
  },
  data() {
    return {
      isOpenData,
      listLoading: false,
      dataList: [],
      columns: fixRole,
      authActionList: [],
      dataAuthList: [],
      userInstance: {}
    };
  },
  mounted() {
    this.fetchUserList();
    this.getAuthList()
  },
  computed: {
    // 权限
    roleManageAuth() {
      return this.btnAuth?.roleManageAuth || false;
    },
    // 是否显示操作按钮
    showOperate() {
      let ret;
      if (this.dataList.length == 1) {
        ret = this.dataList[0].flag != 1;
      } else {
        ret = true;
      }
      return this.roleManageAuth && ret;
    },
  },
  methods: {
    // 获取列表数据
    async fetchUserList() {
      this.listLoading = true;
      try {
        let ret = await projectTypeRoleList({
          projectId: this.projectId,
        });

        const { success, data, message } = ret;
        if (!success) return toast(message, 'error');
          const processedData = data.map(role => {
            // 判断role.language中是否有当前语言的name和description字段，没有的话就使用role的name和description字段生成一个language字段
            if (!role?.language) {
              role.language = {};
            }
            if (!role.language?.[locales.locale]) {
              role.language[locales.locale] = {
                name: role.name,
                description: role.description
              }
            }
            return role;
          });

        this.dataList = processedData || [];
      } catch (err) {
        console.log('error => fetchUserList', err);
      } finally {
        this.listLoading = false;
      }
    },
    // 国际化，处理对象数据
    getNestedProperty(obj, path) {
      const keys = path.split('.');
      return keys.reduce((acc, key) => acc[key], obj);
    },
    // 保存新建角色
    submit(form, isEdit) {
      if (isEdit) {
        roleUpdate(form).then((res) => {
          if (res.success) {
            // 刷新页面
            toast(i18n.t('common.base.tip.updateSuccess'), 'success');
            this.$refs.CreateAuthModal.closeDialog()
            this.fetchUserList()
          } else {
            this.$message.error(res.message)
          }
        })
      } else {
        let params = {
            ...form,
            templateId: this.templateId, // 项目类型id
            projectId: this.projectId, // 项目id
        }
        roleAdd(params).then((res)=> {
          if (!res.success) return this.$message.error(res.message)
          toast(i18n.t('common.base.tip.addSuccess'), 'success');
          this.$refs.CreateAuthModal.closeDialog()
          this.fetchUserList()
        })
      }
    },
    getAuthList()  {
      authList().then((res) => {
        if (res.success)  {
          if (locales.locale != 'zh')
            res.data.forEach((value,item) => {
              res.data[item].name = res.data[item].language[locales.locale].name;
            })
          this.authActionList = res.data || []
          this.dataAuthList = res.data.filter((item) => item.depth === 3)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    chooseUserFunc(params) {
      try {
        projectTypeAddRole({ ...params }).then(res => {
          const { success, data, message } = res;
          if (!success) return toast(message, 'error');

          toast(i18n.t('common.base.tip.addSuccess'), 'success');
          
          this.fetchUserList();
        });
      } catch (err) {
        console.log('error => chooseUserFunc', err);
      }
    },
    // 新建
    handleClickCreate() {
      this.dataAuthList.forEach((item) => {
        item.depth = 3 // 重置为 全部
      })
      this.$refs.CreateAuthModal.openDialog()
    },
    // 编辑
    handleEditRole(item) {
      this.dataAuthList.forEach((item) => {
        item.depth = 3 // 重置为 全部
      })
      roleDetail({roleId: item.id}).then((res) => {
        if (res.success) {
          let detailData = res.data || {}
          this.dataAuthList.forEach((item) => {
            detailData.auths.forEach((ele) => {
              if (item.id === ele.id) {
                item.depth = ele.depth
              }
            })
          })
          this.$refs.CreateAuthModal.openDialog(detailData, true)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 删除
    handleDeleteRole(row) {
      let params = {
        roleId: row.id,
        templateId: this.templateId, // 项目类型id
      };

      MessageBox.confirm(this.$t('projectManage.setting.deleteTip1'), this.$t('common.base.toast'), {
        confirmButtonText: i18n.t('common.base.makeSure'),
        cancelButtonText: i18n.t('common.base.cancel'),
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            roleDelete({ ...params }).then(res => {
              instance.confirmButtonLoading = false;

              if (!res.success) {
                return toast(res.message, 'error');
              }

              toast(i18n.t('common.base.tip.deleteSuccess'), 'success');

              done();

              this.fetchUserList();
            });
          } else {
            instance.confirmButtonLoading = false;
            done();
          }
        },
      });
    },
    jumpDetail () {
      this.$emit('jumpPersonTab')
      // 关闭人员控件
      this.userInstance.close()
    },
    // 添加人员
    chooseUser(row) {
      const selectUser = (row.userList || []).map(item => {
        return {
          displayName: item.displayName,
          userId: item.userId,
          staffId: item.staffId,
        };
      });

      let options = {
        title: i18n.t('common.projectManage.detail.selectRole'),  // [选填] 默认值为 '请选择人员'
        max: -1, // [选填]最大人数：当值小于等于0或者不填时，不对选择人数做限制，max值为1时单选，大于1时多选
        selectedUsers: selectUser, // [选填] 已选人员 每个人员必须包括userId,displayName,staffId,head这四个属性，只有带max大于1时生效
        isScreenSelect: false,
        showDepartment: false,
        showRole: false,
        showServiceProvider: false,
        showProjectTeam: true,
        mode: BaseSelectUserModeEnum.Filter,
        renderDynamicContent: (h, context) => {
          return (
            <div class="projectCustom">
              <span class="projectCustom-left">{i18n.t('common.projectManage.detail.selectProjectTeam')}</span>
              <span class="projectCustom-right" onClick={this.jumpDetail}>{i18n.t('common.projectManage.detail.setProjectTeam')}</span>
            </div>
          )
        },
        getInstance: (instance) => {
          this.userInstance = instance;    
        },
        fetchProjectTeamList: () => { 
          const newParams = {
            projectId: this.projectId
          }
          return getSelectProjectTeamList(newParams)
        },
        fetchProjectTeamUserList: () => {
          const newParams = {
            projectId: this.projectId
          }
          return getMemberList(newParams)
        },
        fetchSearchUserList: (params)=>{
          const newParams = {
            ...params,
            projectId:this.projectId
          }
          return getSearchUserList(newParams)
        },
        fetchSearchMoreUserList:(params)=>{
          const newParams = {
            ...params,
            projectId:this.projectId
          }
          return getSearchMoreUserList(newParams)
        },
      };

      this.$fast.select.multi
        .user(options)
        .then(res => {
          if (res.status != 0 || !res.data) return;

          let list = res.data.users || [];

          let userIds = list.map(item => item.userId);

          const params = {
            projectId: this.projectId,
            roleId: row.id,
            userIds,
          };

          this.chooseUserFunc(params);
        })
        .catch(err => {
          console.error(err);
        });
    },
  },
};
</script>
<style lang="scss">
  .projectCustom {
    padding: 6px 12px 6px 20px;
    &-left {

    }
    &-right {
      color: $color-primary-light-6;
      cursor: pointer;
      margin-left: 10px;
      &:hover {
        text-decoration: underline;
      }
    }
  }
</style>
<style lang="scss" scoped>
.project-type-role-manage {
  ::v-deep .el-button--mini {
    border-radius: 4px;
  }

  .operation-button {
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
  .edit {
    color: $color-primary;
  }
  .delete {
    color: $color-danger;
  }
}
</style>